package cn.tedu.web.service.impl;

import cn.tedu.web.entity.Address;
import cn.tedu.web.entity.Order;
import cn.tedu.web.entity.OrderDetail;
import cn.tedu.web.entity.StorageOrder;
import cn.tedu.web.mapper.OrderMapper;
import cn.tedu.web.service.IAddressService;
import cn.tedu.web.service.IOrderService;

import java.util.List;

import javax.annotation.Resource;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 【订单表】 服务实现类
 * </p>
 *
 * @author issen
 * @since 2021-10-18
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Resource
    private OrderMapper orderMapper;
    @Resource
    private IAddressService addressService;

    @Transactional
    public Order create(StorageOrder storage, Integer uid) {
        if (storage == null || uid == null) {
            return null;
        }
        List<OrderDetail> details = storage.getDetails();
        if (details == null || details.isEmpty()) {
            return null;
        }
        // 保存地址
        Address address = storage.getAddress();
        address.setUid(uid);
        addressService.save(address);
        // 从临时存储的订单中提炼出订单对象
        Order order = storage.getOrder(uid);
        // 插入订单信息，并返回受影响的行数
        Integer affectRows = orderMapper.insertOrder(order);
        for (OrderDetail detail : details) {
            detail.setOid(order.getId());
            affectRows += orderMapper.insertOrderDetail(detail);
        }
        System.out.println("保存完成，受影响的行数为：" + affectRows);

        return order;
    }

}
